<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Moon, Sunny, User, Setting, SwitchButton, Clock, Delete, Document, Reading, HomeFilled } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Background from './components/common/Background.vue'
import Sidebar from './components/common/Sidebar.vue'
import CustomCursor from './components/CustomCursor.vue'
import FontStyles from './components/common/FontStyles.vue'

const router = useRouter()
const route = useRoute()
const isDark = ref(false)
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
const userAvatar = ref(null)
const sidebarRef = ref(null)
const isSidebarCollapsed = ref(false)
const isMobile = ref(false)
const showCustomCursor = ref(false)

// 最近访问记录
const recentVisits = ref([])
const MAX_RECENT_VISITS = 5

const isAuthenticated = computed(() => {
  return localStorage.getItem('access_token') !== null
})

const currentPageTitle = computed(() => {
  const routeTitles = {
    '/dashboard': '仪表盘',
    '/dashboard/documents': '文档列表',
    '/dashboard/upload': '上传文档',
    '/dashboard/shared': '共享文档',
    '/dashboard/profile': '个人信息',
    '/dashboard/settings': '系统设置',
    '/dashboard/about': '关于系统',
    '/dashboard/exercises': '练习集列表',
    '/dashboard/exercises/my-exercises': '我的练习',
    '/dashboard/exercises/recent': '最近练习',
    '/dashboard/exercises/statistics': '练习统计',
    '/dashboard/exercises/create': '创建练习集'
  }
  return routeTitles[route.path] || '文档管理系统'
})

// 获取路由对应的图标
const getRouteIcon = (path) => {
  const routeIcons = {
    '/dashboard': 'HomeFilled',
    '/dashboard/documents': 'Document',
    '/dashboard/upload': 'Upload',
    '/dashboard/shared': 'Share',
    '/dashboard/profile': 'User',
    '/dashboard/settings': 'Setting',
    '/dashboard/about': 'InfoFilled',
    '/dashboard/exercises': 'Reading',
    '/dashboard/exercises/my-exercises': 'Reading',
    '/dashboard/exercises/recent': 'Clock',
    '/dashboard/exercises/statistics': 'DataAnalysis',
    '/dashboard/exercises/create': 'Edit'
  }
  return routeIcons[path] || 'Document'
}

// 添加到最近访问
const addToRecentVisits = (path) => {
  // 如果是登录页或已经在最近访问的第一位，则不添加
  if (path === '/login' || (recentVisits.value.length > 0 && recentVisits.value[0].path === path)) {
    return
  }
  
  // 获取路由标题
  const title = currentPageTitle.value
  const icon = getRouteIcon(path)
  
  // 移除已存在的相同路径项
  const existingIndex = recentVisits.value.findIndex(item => item.path === path)
  if (existingIndex !== -1) {
    recentVisits.value.splice(existingIndex, 1)
  }
  
  // 添加到最前面
  recentVisits.value.unshift({ path, title, icon })
  
  // 限制数量
  if (recentVisits.value.length > MAX_RECENT_VISITS) {
    recentVisits.value = recentVisits.value.slice(0, MAX_RECENT_VISITS)
  }
  
  // 保存到本地存储
  saveRecentVisits()
}

// 保存最近访问到本地存储
const saveRecentVisits = () => {
  localStorage.setItem('recentVisits', JSON.stringify(recentVisits.value))
}

// 加载最近访问
const loadRecentVisits = () => {
  const saved = localStorage.getItem('recentVisits')
  if (saved) {
    try {
      recentVisits.value = JSON.parse(saved)
    } catch (e) {
      console.error('Failed to parse recent visits:', e)
      recentVisits.value = []
    }
  }
}

// 清除最近访问记录
const clearRecentVisits = () => {
  ElMessageBox.confirm(
    '确定要清除所有最近访问记录吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    recentVisits.value = []
    localStorage.removeItem('recentVisits')
    ElMessage.success('已清除所有最近访问记录')
  }).catch(() => {})
}

// 监听路由变化，更新最近访问
watch(
  () => route.path,
  (newPath) => {
    if (isAuthenticated.value) {
      addToRecentVisits(newPath)
    }
  }
)

const toggleDark = (value) => {
  if (value) {
    document.documentElement.classList.add('dark')
  } else {
    document.documentElement.classList.remove('dark')
  }
}

const handleCommand = (command) => {
  switch (command) {
    case 'profile':
      router.push('/dashboard/profile')
      break
    case 'settings':
      router.push('/dashboard/settings')
      break
    case 'logout':
      localStorage.removeItem('access_token')
      localStorage.removeItem('refresh_token')
      localStorage.removeItem('username')
      ElMessage.success('已退出登录')
      router.push('/login').then(() => {
        setTimeout(() => {
          window.location.reload()
        }, 100)
      })
      break
  }
}

const handleSidebarCollapse = (collapsed) => {
  isSidebarCollapsed.value = collapsed
}

const checkMobile = () => {
  isMobile.value = window.innerWidth <= 768
  // 更新自定义光标的显示状态
  showCustomCursor.value = !isMobile.value
}

onMounted(() => {
  // 确保应用深色主题
  document.documentElement.classList.add('dark')
  isDark.value = true
  
  // 检测是否为移动设备
  checkMobile()
  
  // 在非移动设备上启用自定义光标
  showCustomCursor.value = !isMobile.value
  
  // 加载最近访问记录
  loadRecentVisits()
  
  // 添加当前页面到最近访问
  if (isAuthenticated.value && route.path !== '/login') {
    addToRecentVisits(route.path)
  }
  
  window.addEventListener('resize', checkMobile)
})

onUnmounted(() => {
  window.removeEventListener('resize', checkMobile)
})
</script>

<template>
  <div class="app-container">
    <FontStyles />
    <Background />
    <Sidebar v-if="isAuthenticated" ref="sidebarRef" @collapse-change="handleSidebarCollapse" />
    <div class="main-container" :class="{ 'sidebar-collapsed': isSidebarCollapsed, 'mobile': isMobile, 'no-sidebar': !isAuthenticated }">
      <template v-if="isAuthenticated">
        <el-header class="app-header">
          <div class="header-left">
            <h2 class="important-feature">{{ currentPageTitle }}</h2>
            
            <!-- 最近访问下拉菜单 -->
            <el-dropdown class="recent-visits-dropdown" trigger="click">
              <div class="recent-visits-trigger">
                <el-icon><Clock /></el-icon>
                <span>最近访问</span>
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <div v-if="recentVisits.length > 0">
                    <el-dropdown-item 
                      v-for="(item, index) in recentVisits" 
                      :key="index" 
                      @click="router.push(item.path)"
                    >
                      <div class="recent-visit-item">
                        <el-icon><component :is="item.icon" /></el-icon>
                        <span>{{ item.title }}</span>
                      </div>
                    </el-dropdown-item>
                    <el-dropdown-item divided>
                      <div class="clear-recent" @click.stop="clearRecentVisits">
                        <el-icon><Delete /></el-icon>
                        <span>清除历史记录</span>
                      </div>
                    </el-dropdown-item>
                  </div>
                  <el-dropdown-item v-else disabled>
                    <span>暂无最近访问记录</span>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
          <div class="header-right">
            <el-dropdown @command="handleCommand">
              <el-avatar 
                :size="32"
                :src="userAvatar || defaultAvatar"
              />
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="profile">
                    <el-icon><User /></el-icon>
                    个人信息
                  </el-dropdown-item>
                  <el-dropdown-item command="settings">
                    <el-icon><Setting /></el-icon>
                    系统设置
                  </el-dropdown-item>
                  <el-dropdown-item divided command="logout">
                    <el-icon><SwitchButton /></el-icon>
                    退出登录
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>

            <el-switch
              v-model="isDark"
              class="ml-2"
              style="margin-left: 16px"
              inline-prompt
              :active-icon="Moon"
              :inactive-icon="Sunny"
              @change="toggleDark"
            />
          </div>
        </el-header>
        
        <el-main class="app-main">
          <router-view v-slot="{ Component }">
            <transition name="fade" mode="out-in">
              <component :is="Component" />
            </transition>
          </router-view>
        </el-main>
      </template>
      
      <router-view v-else />
    </div>
    
    <!-- 自定义光标组件 -->
    <CustomCursor v-if="showCustomCursor" style="pointer-events: none;" />
  </div>
</template>

<style>
/* 全局样式 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "KaiTi", "楷体", serif;
}

body {
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: #000;
  font-family: "KaiTi", "楷体", serif;
}

#app {
  min-height: 100vh;
}

/* Element Plus 暗色主题覆盖 */
:root {
  --el-color-primary: #6B46C1;
  --el-color-primary-light-3: #805AD5;
  --el-color-primary-light-5: #9F7AEA;
  --el-color-primary-light-7: #B794F4;
  --el-color-primary-light-9: #D6BCFA;
  --el-color-primary-dark-2: #553C9A;
}

/* 布局样式 */
.app-container {
  min-height: 100vh;
  display: flex;
}

.main-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background: transparent;
  margin-left: 240px;
  transition: margin-left 0.3s ease;
  position: relative;
  z-index: 1;
  pointer-events: auto;
}

.main-container.sidebar-collapsed {
  margin-left: 64px;
}

.main-container.mobile {
  margin-left: 0;
}

.main-container.no-sidebar {
  margin-left: 0;
  justify-content: center;
  align-items: center;
}

/* 未登录状态下的内容居中 */
.main-container.no-sidebar > * {
  max-width: 100%;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.app-header {
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(10px);
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  height: 60px;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.header-left h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: black;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

/* 最近访问样式 */
.recent-visits-dropdown {
  margin-left: 10px;
}

.recent-visits-trigger {
  display: flex;
  align-items: center;
  gap: 6px;
  cursor: pointer;
  padding: 6px 10px;
  border-radius: 4px;
  transition: all 0.3s;
  color: #333;
}

.recent-visits-trigger:hover {
  background: rgba(107, 70, 193, 0.1);
}

.recent-visit-item {
  display: flex;
  align-items: center;
  gap: 8px;
  width: 100%;
}

.clear-recent {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #f56c6c;
  width: 100%;
}

.app-main {
  padding: 20px;
  flex: 1;
  overflow-y: auto;
  position: relative;
  z-index: 10;
  pointer-events: auto;
}

/* 页面切换动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 全局滚动条样式 */
::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
}

::-webkit-scrollbar-thumb {
  background: rgba(107, 70, 193, 0.3);
  border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
  background: rgba(107, 70, 193, 0.5);
}

/* 深色模式适配 */
.dark {
  --el-bg-color: #1a1a1a;
  --el-text-color-primary: #000000;
  --el-text-color-regular: #333333;
  --el-border-color-lighter: #404040;
}

.dark .el-card {
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
}

.dark .el-table {
  background: transparent;
}

.dark .el-table th,
.dark .el-table tr {
  background: rgba(255, 255, 255, 0.05);
}

.dark .el-table--striped .el-table__body tr.el-table__row--striped td {
  background: rgba(255, 255, 255, 0.02);
}

/* 全局卡片样式 */
.el-card {
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
  margin-bottom: 20px;
}

.el-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
}

.el-card__header {
  padding: 16px 20px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.el-card__body {
  padding: 20px;
}

/* 全局表格样式 */
.el-table {
  border-radius: 8px;
  overflow: hidden;
}

.el-table th {
  background-color: rgba(255, 255, 255, 0.05) !important;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.el-table td, .el-table th.is-leaf {
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.el-table--border, .el-table--group {
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.el-table--border .el-table__cell {
  border-right: 1px solid rgba(255, 255, 255, 0.1);
}

/* 按钮样式优化 */
.el-button {
  border-radius: 6px;
  transition: all 0.3s ease;
}

.el-button--primary {
  background-color: var(--el-color-primary);
  border-color: var(--el-color-primary);
  box-shadow: 0 4px 12px rgba(107, 70, 193, 0.3);
}

.el-button--primary:hover {
  background-color: var(--el-color-primary-light-3);
  border-color: var(--el-color-primary-light-3);
  box-shadow: 0 6px 16px rgba(107, 70, 193, 0.5);
  transform: translateY(-2px);
}

.el-button--success {
  background-color: #10B981;
  border-color: #10B981;
  box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);
}

.el-button--success:hover {
  background-color: #34D399;
  border-color: #34D399;
  box-shadow: 0 6px 16px rgba(16, 185, 129, 0.5);
  transform: translateY(-2px);
}

.el-button--danger {
  background-color: #EF4444;
  border-color: #EF4444;
  box-shadow: 0 4px 12px rgba(239, 68, 68, 0.3);
}

.el-button--danger:hover {
  background-color: #F87171;
  border-color: #F87171;
  box-shadow: 0 6px 16px rgba(239, 68, 68, 0.5);
  transform: translateY(-2px);
}

.el-button--warning {
  background-color: #F59E0B;
  border-color: #F59E0B;
  box-shadow: 0 4px 12px rgba(245, 158, 11, 0.3);
}

.el-button--warning:hover {
  background-color: #FBBF24;
  border-color: #FBBF24;
  box-shadow: 0 6px 16px rgba(245, 158, 11, 0.5);
  transform: translateY(-2px);
}

.el-button--info {
  background-color: #6B7280;
  border-color: #6B7280;
  box-shadow: 0 4px 12px rgba(107, 114, 128, 0.3);
}

.el-button--info:hover {
  background-color: #9CA3AF;
  border-color: #9CA3AF;
  box-shadow: 0 6px 16px rgba(107, 114, 128, 0.5);
  transform: translateY(-2px);
}

/* 响应式布局 */
@media (max-width: 768px) {
  .main-container {
    margin-left: 0;
  }
  
  .sidebar {
    transform: translateX(-100%);
  }
  
  .sidebar.visible {
    transform: translateX(0);
  }
}

/* 表格中的操作按钮样式 */
.el-table .el-button.is-link {
  font-weight: 500;
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.el-table .el-button.is-link:hover {
  background-color: rgba(255, 255, 255, 0.1);
  transform: scale(1.05);
}

.el-table .el-button.is-link.el-button--primary {
  color: var(--el-color-primary);
}

.el-table .el-button.is-link.el-button--primary:hover {
  color: var(--el-color-primary-light-3);
}

.el-table .el-button.is-link.el-button--danger {
  color: #EF4444;
}

.el-table .el-button.is-link.el-button--danger:hover {
  color: #F87171;
}

.el-table .el-button.is-link.el-button--success {
  color: #10B981;
}

.el-table .el-button.is-link.el-button--success:hover {
  color: #34D399;
}

/* 标签样式优化 */
.el-tag {
  border-radius: 4px;
  font-weight: 500;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.el-tag:hover {
  transform: translateY(-1px);
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.15);
}

.el-tag--primary {
  background-color: rgba(107, 70, 193, 0.15);
  border-color: rgba(107, 70, 193, 0.3);
  color: var(--el-color-primary-light-3);
}

.el-tag--success {
  background-color: rgba(16, 185, 129, 0.15);
  border-color: rgba(16, 185, 129, 0.3);
  color: #10B981;
}

.el-tag--warning {
  background-color: rgba(245, 158, 11, 0.15);
  border-color: rgba(245, 158, 11, 0.3);
  color: #F59E0B;
}

.el-tag--danger {
  background-color: rgba(239, 68, 68, 0.15);
  border-color: rgba(239, 68, 68, 0.3);
  color: #EF4444;
}

.el-tag--info {
  background-color: rgba(107, 114, 128, 0.15);
  border-color: rgba(107, 114, 128, 0.3);
  color: #9CA3AF;
}

/* Element Plus 组件字体覆盖 */
:deep(.el-button),
:deep(.el-input__inner),
:deep(.el-textarea__inner),
:deep(.el-form-item__label),
:deep(.el-dialog__title),
:deep(.el-message-box__title),
:deep(.el-dropdown-menu__item),
:deep(.el-menu-item),
:deep(.el-sub-menu__title),
:deep(.el-table th),
:deep(.el-table td),
:deep(.el-pagination),
:deep(.el-tag),
:deep(.el-select-dropdown__item),
:deep(.el-radio__label),
:deep(.el-checkbox__label) {
  font-family: "KaiTi", "楷体", serif !important;
}
</style>
